/**
 * 
 */
package hu.cubussapiens.facts.query;

import hu.cubussapiens.facts.StringData;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author balage
 *
 */
public class CreateLiteral implements Query {

	final String literal;
	final Long read;
	
	public CreateLiteral(String literal, Long readAccess) {
		this.literal = literal;
		this.read = readAccess;
	}
	
	/* (non-Javadoc)
	 * @see hu.cubussapiens.facts.query.Query#execute(hu.cubussapiens.facts.query.IQueryContext)
	 */
	@Override
	public List<Long> execute(IQueryContext context) {
		List<Long> result = new ArrayList<Long>(1);
		
		StringData sd = context.getLiteral(literal);
		if (sd != null){
			if (context.canAccess(sd.getRead()));
				result.add(sd.getId());
		}else if (context.canAccess(read)){
			sd = new StringData();
			sd.setData(literal);
			sd.setDate(new Date());
			sd.setRead(read);
			context.getManager().makePersistent(sd);
			result.add(sd.getId());
		}
		
		return result;
	}

}
